package com.hboxs.asl.controller.app.index;

import com.hboxs.asl.Filter;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Setting;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.PhonePatternUtils;
import com.hboxs.asl.util.SettingUtils;
import com.hboxs.asl.util.SpringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by xxx on 2016/11/25.
 * Controller -- 用户管理
 */
@Controller(value = "appMemberController")
@RequestMapping(value = "/app/member")
public class MemberController extends BaseController {

    @Resource(name = "verificationCodeServiceImpl")
    private VerificationCodeService verificationCodeService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "memberRankServiceImpl")
    private MemberRankService memberRankService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;
    @Resource(name = "globalConfigServiceImpl")
    private GlobalConfigService globalConfigService;
    @Resource(name = "memberCertificationServiceImpl")
    private MemberCertificationService memberCertificationService;
    @Resource(name = "commonContentServiceImpl")
    private CommonContentService commonContentService;

    /**
     * ios设置clientId
     * @param clientId
     * @return
     */
    @RequestMapping(value = "/setClientid", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage setClientid(String clientId) {
        Member member = memberService.getCurrentByToken();
        if (member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }
        if (clientId != null) {
            List<Member> memberList = memberService.findListByClientId(clientId);
            if (memberList.size() > 0) {
                for (Member memberClientId : memberList) {
                    memberClientId.setClientId(null);
                    memberService.update(memberClientId);
                }
            }
//            Member member1 = memberService.findByClientId(clientId);
//            if (member1 != null) {
//                member1.setClientId(null);
//                memberService.update(member1);
//            }
        }
        member.setClientId(clientId);
        memberService.update(member);
        return JsonMessage.success();
    }

    /**
     * 第三方登录(QQ/微信/)
     * 涉及页面: 登录
     *
     * @param openId qq,微信openid
     * @return Json
     */
    @RequestMapping(value = "/thPartyLogin", method = RequestMethod.POST)
    public
    @ResponseBody
    Object thPartyLogin(String openId, String avator,  String name, HttpServletRequest request, String clientId) {

        try {
            if (openId == null) {
                return JsonMessage.error("openId不能为空");
            }
            Member member = memberService.findByUsername(openId);
            if (member == null) {
                member = new Member();
                member.setIsEnabled(true);
                member.setIsLocked(false);
                member.setLoginFailureCount(0);
                member.setUsername(openId);
                member.setPassword(DigestUtils.md5Hex("123456"));
                member.setRegisterIp(request.getRemoteAddr());
                member.setPoint(new BigDecimal(0));
                member.setAmount(new BigDecimal(0));
                member.setBalance(new BigDecimal(0));
                member.setType(Member.Type.member);
                member.setIsTop(false);
                member.setClientId(clientId);
                member.setPoint(globalConfigService.getUniqueness().getPoint());
            }

            //更新用户资料
            member.setName(name == null ? member.getName() : name);
            member.setAvator(avator == null ? member.getAvator() : avator);
            memberService.save(member);
            return submit(openId, member.getPassword(), request, clientId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }



    /**
     * 用户注册
     *
     * @param username 用户名(用户名就是用户名,用邮箱还是用手机都是用户名!!!!!!!)
     * @param captcha  验证码
     * @param password 密码
     * @return json
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage register(String username, String captcha, String password, HttpServletRequest request) {
            if (StringUtils.isEmpty(username)) {
                return JsonMessage.error("手机号不能为空");
            }
            if (memberService.usernameExists(username)) {
                return JsonMessage.error("该手机号已经注册");
            }
            if (!PhonePatternUtils.isChinaPhoneLegal(username)) {
                return JsonMessage.error("手机号码无效");
            }
            List<Filter> filters = new ArrayList<>();
            filters.add(Filter.eq("phone", username));
            List<VerificationCode> codes = verificationCodeService.findList(1, filters, null);
            String sendCode = null;
            if (codes != null) {
                for (VerificationCode verificationCode : codes) {
                    sendCode = verificationCode.getCode();
                }
            }

            if (!captcha.equalsIgnoreCase(sendCode)) {
                return JsonMessage.error("手机验证码不正确");
            }
            if (StringUtils.isEmpty(password)) {
                return JsonMessage.error("密码不能为空");
            }

            //认证
            MemberCertification memberCertification = new MemberCertification();
            memberCertificationService.save(memberCertification);

            Member member = new Member();
            member.setMemberCertification(memberCertification);
            member.setUsername(username);
            member.setEmail("@");
            member.setPhone(null);
            member.setPassword(password);
            member.setAvator(null);
            member.setType(Member.Type.member);
            member.setPoint(globalConfigService.getUniqueness().getPoint());
            member.setIsTop(false);
            member.setAmount(new BigDecimal(0));
            member.setBalance(new BigDecimal(0));
            member.setIsEnabled(true);
            member.setIsLocked(false);
            member.setLoginFailureCount(0);
            member.setLockedDate(null);
            member.setRegisterIp(request.getRemoteAddr());
            member.setLoginIp(request.getRemoteAddr());
            member.setLoginDate(new Date());
            member.setSafeKey(null);
            member.setMemberRank(memberRankService.findDefault());
            member.setFavoriteProducts(null);
            member.setClientId(null);
            memberService.save(member);
            member.setName(member.getID().toString());
            memberService.update(member);

            Cart cart = cartService.getCurrentByToken();
            if (cart != null && cart.getMember() == null) {
                cartService.merge(member, cart);
            }
            return JsonMessage.success("注册成功");
    }

    /**
     * 获取所有注册标签
     * @return
     */
    @RequestMapping(value = "/registerTags", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage registerTags() {
        try {
            GlobalConfig globalConfig = globalConfigService.getUniqueness();
            return JsonMessage.success(JsonMessage.optimiseObj(globalConfig, "registerTag"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 保存注册标签
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage save(String introduction, String tags, String username) {
        try {
            Member member = memberService.findByUsername(username);
            member.setTags(tags);
            member.setIntroduction(introduction);
            memberService.update(member);
            return JsonMessage.success("保存成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 绑定手机号码
     * @param phone
     * @return
     */
    @RequestMapping(value = "/bind", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage bind(String phone) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            member.setPhone(phone);
            memberService.update(member);
            return JsonMessage.success("绑定成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 用户登录(若需要做未登录的购物车,request需要传id和key)
     *
     * @param username 手机
     * @param password 密码
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public
    @ResponseBody
    Object submit(String username, String password, HttpServletRequest request, String clientId) {

        try {
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                return JsonMessage.error("用户名或密码不能为空");
            }

            Setting setting = SettingUtils.get();
            Member member = memberService.findByUsername(username);

            if (member == null) {
                logger.error(SpringUtils.getMessage("shop.login.unknownAccount"));
                return JsonMessage.error("此账号不存在");
            }
            if (!member.getIsEnabled()) {
                logger.error(SpringUtils.getMessage("shop.login.disabledAccount"));
                return JsonMessage.error("此账号已被禁用");
            }
            if (member.getIsLocked()) {
                if (ArrayUtils.contains(setting.getAccountLockTypes(), Setting.AccountLockType.member)) {
                    int loginFailureLockTime = setting.getAccountLockTime();
                    if (loginFailureLockTime == 0) {
                        logger.error(SpringUtils.getMessage("shop.login.lockedAccount"));
                        return JsonMessage.error("此账号已被锁定");
                    }
                    Date lockedDate = member.getLockedDate();
                    Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
                    if (new Date().after(unlockDate)) {
                        member.setLoginFailureCount(0);
                        member.setIsLocked(false);
                        member.setLockedDate(null);
                        memberService.update(member);
                    } else {
                        logger.error(SpringUtils.getMessage("shop.login.lockedAccount"));
                        return JsonMessage.error("此账号已被锁定");
                    }
                } else {
                    member.setLoginFailureCount(0);
                    member.setIsLocked(false);
                    member.setLockedDate(null);
                    memberService.update(member);
                }
            }
            if (!password.equals(member.getPassword())) {
                int loginFailureCount = member.getLoginFailureCount() + 1;
                if (loginFailureCount >= setting.getAccountLockCount()) {
                    member.setIsLocked(true);
                    member.setLockedDate(new Date());
                }
                member.setLoginFailureCount(loginFailureCount);
                memberService.update(member);
                if (ArrayUtils.contains(setting.getAccountLockTypes(), Setting.AccountLockType.member)) {
                    logger.error(SpringUtils.getMessage("admin.login.emailLockCount", setting.getAccountLockCount()));
                    return JsonMessage.error("密码错误，若连续" + setting.getAccountLockCount() + "次密码错误账号将被锁定");
                } else {
                    logger.error(SpringUtils.getMessage("shop.login.incorrectCredentials"));
                    return JsonMessage.error("用户名或密码错误");
                }
            }

            //clientId操作
            if (clientId != null) {
//                Member member1 = memberService.findByClientId(clientId);
//                if (member1 != null) {
//                    member1.setClientId(null);
//                    memberService.update(member1);
//                }
                List<Member> memberList = memberService.findListByClientId(clientId);
                if (memberList.size() > 0) {
                    for (Member memberClientId : memberList) {
                        memberClientId.setClientId(null);
                        memberService.update(memberClientId);
                    }
                }
                member.setClientId(clientId);
            }

            member.setLoginIp(request.getRemoteAddr());
            member.setLoginDate(new Date());
            member.setLoginFailureCount(0);

            memberService.update(member);

            //登录生成token
            member.setToken(UUID.randomUUID().toString());
            member.setTokenExpire(DateUtils.addDays(new Date(), MEMBER_LOGIN_EXPIRED_DAY));
            memberService.update(member);

            return JsonMessage.success(
                    "ID", member.getID()
                    , "type", member.getType()
                    , "token", member.getToken()
                    , "tokenExpire", member.getTokenExpire()
                    , "name", member.getName()
                    , "avator", member.getAvator()
                    , "myFans", member.getFavorMembers().size()
                    , "point", member.getPoint()
                    , "balance", member.getBalance()
                    , "earnings", member.getEarnings()
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 用户退出登录
     *
     * @return json
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage logout() {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            member.setClientId(null);
            member.setToken(null);
            member.setTokenExpire(null);
            memberService.update(member);
            return JsonMessage.success("用户退出成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 注册协议
     * @return
     */
    @RequestMapping(value = "/protocol", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage protocol(HttpServletRequest request) {
        try {
            String path = request.getRequestURL().toString();
            int index = path.lastIndexOf("/protocol");
            String contentPath = path.substring(0, index);
            String url =  contentPath + "/registration_protocol_web.htm";
            return JsonMessage.success(url);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 注册协议h5
     *
     * @return
     */
    @RequestMapping(value = "/registration_protocol_web", method = RequestMethod.GET)
    public
    String detail(ModelMap modelMap) {
        CommonContent commonContent = commonContentService.getUniqueness();
        modelMap.addAttribute("commonContent" ,commonContent);
        return "/yijing/registration_protocol_web";
    }

    /**
     * 关于我们h5
     * @param model
     * @return
     */
    @RequestMapping(value = "/about", method = RequestMethod.GET)
    public String about(ModelMap model) {
        CommonContent commonContent = commonContentService.getUniqueness();
        model.addAttribute("commonContent", commonContent);
        return "/yijing/about";
    }

    /**
     * 提现说明h5
     * @param model
     * @return
     */
    @RequestMapping(value = "/cash", method = RequestMethod.GET)
    public String cash(ModelMap model) {
        CommonContent commonContent = commonContentService.getUniqueness();
        model.addAttribute("commonContent", commonContent);
        return "/yijing/cash_declaration";
    }

    /**
     * 测试token是否过期,返回token
     *
     * @param username 用户名
     * @return json
     */
    @RequestMapping(value = "/isExpiredToken", method = RequestMethod.GET)
    public
    @ResponseBody
    Object getExpiredTokens(String username) {

        try {
            Member member = memberService.findByUsername(username);
            if (member == null) {
                return JsonMessage.error("找不到该用户");
            }

            Date date = new Date();

            if (member.getTokenExpire() != null) {
                if (member.getTokenExpire().before(date)) {
                    return JsonMessage.success("令牌已过期");
                } else {
                    return JsonMessage.success("token", member.getToken().equals("") ? null : member.getToken());
                }
            } else {
                return JsonMessage.error("令牌过期时间为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
